package houduan;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "PostServlet", urlPatterns = {"/PostServlet"})
public class PostServlet extends HttpServlet {

    // 数据库连接信息
    private static final String DB_URL = "jdbc:mysql://localhost:3306/lczmysql?useUnicode=true&characterEncoding=utf-8";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    // 获取数据库连接的方法
    private Connection getConnection() throws SQLException, ClassNotFoundException {
        // 加载数据库驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }

    // 处理 POST 请求
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        // 获取请求中的表单数据
        String title = request.getParameter("title");
        String content = request.getParameter("editorValue");  // UEditor 编辑器内容
        String author = request.getParameter("author");
        String category = request.getParameter("category");

        // 打印出内容调试（如果内容为空，查看是否正确接收到）
        System.out.println("Title: " + title);
        System.out.println("Content: " + content);
        System.out.println("Author: " + author);
        System.out.println("Category: " + category);

        // 将数据存入数据库
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            // 获取数据库连接
            conn = getConnection(); // 调用封装的连接方法

            // SQL 插入语句
            String sql = "INSERT INTO post (title, content, author, category) VALUES (?, ?, ?, ?)";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, title);
            stmt.setString(2, content);
            stmt.setString(3, author);
            stmt.setString(4, category);

            // 执行插入操作
            int rowsAffected = stmt.executeUpdate();
            if (rowsAffected > 0) {
                // 插入成功，重定向到成功页面或返回成功消息
                response.sendRedirect("./index.jsp");  // 你可以根据需要修改
            } else {
                response.getWriter().write("发布失败，请稍后再试！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().write("数据库错误：" + e.getMessage());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            response.getWriter().write("数据库驱动错误：" + e.getMessage());
        } finally {
            // 关闭数据库资源
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 可以调用 doPost 方法或者重定向到登录页面
        this.doPost(request, response);
    }
}
